package com.jusfoun.communication.dao.impl;

import com.jusfoun.communication.constant.MessageConstant;
import com.jusfoun.communication.constant.RedisKeyConstant;
import com.jusfoun.communication.dao.MessageDao;
import com.jusfoun.communication.model.Message;
import com.jusfoun.communication.util.PageInfo;
import com.jusfoun.communication.util.RedisUtil;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 分布式环境下messageDao
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2017-12-12 15:46
 **/
@Component
public class MessageDaoDistributImpl extends MessageDaoImpl {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${server.name}")
    private String serverName;

    @Override
    public Message push4Send(Message message) {
        if (StringUtils.isNotBlank(message.getAppId()) && StringUtils.isNotBlank(message.getTo())) {
            String thisServerName = redisUtil.getItem(RedisKeyConstant.REDIS_USER_SERVER + message.getAppId() + ":" + message.getTo());
            //先获取当前用户所在的服务器
            if (StringUtils.isNotBlank(thisServerName)) {
                redisUtil.leftPush(RedisKeyConstant.REDIS_MESSAGE_NEED_PUSH + ":" + thisServerName, String.valueOf(message.getId()));
            } else {
                push4OffLine(message);
            }
            return message;
        } else {
            return null;
        }
    }

    @Override
    public Long getMsgId4Send() {
        String id = redisUtil.rightPop(RedisKeyConstant.REDIS_MESSAGE_NEED_PUSH + ":" + serverName, 1, TimeUnit.MINUTES);
        if (StringUtils.isNotBlank(id)) {
            return Long.valueOf(id);
        }
        return null;
    }

    @Override
    public void dealLoginMsg(String appId, String userName) {
        redisUtil.saveItem(RedisKeyConstant.REDIS_USER_SERVER + appId + ":" + userName, serverName);
    }

    @Override
    public void dealLogoutMsg(String appId, String userName) {
        redisUtil.removeItem(RedisKeyConstant.REDIS_USER_SERVER + appId + ":" + userName);
    }
}
